
const FileSystem = require("fs").promises
const Http = require("http")
async function get(options){
    let buffer
    return new Promise((resolve, reject) => {
        const chunks = []
        const request = Http.request({
            ...options,

        }, res => {
            res.on("data", chunk => {
                chunks.push(chunk)
            })
            res.on("end", () => {
                resolve(Buffer.concat(chunks))
            })
            res.on("error", reject)
        })
        request.end()
    })
}
async function getMetaData(packageName) {
    const data = await get({
        // schema: "http",
        host: "registry.npm.taobao.org",
        path: "/" + packageName,
        method: "GET"
    })
    return JSON.parse(data.toString())
}
async function  updateVersion(dependencyObject) {
    const dependencies = Object.keys(dependencyObject).map(value => {
        console.log(value)
        return {
            key: value,
            value: getMetaData(value)
        }
    })
    console.log("***********")
    for (const item of dependencies) {
        item.value = await item.value.then(item => item["dist-tags"].latest)
        dependencyObject[item.key] = item.value
        console.log(`${item.key} : ${item.value} -> [OK]`)
    }
}
async function main() {
    let json = await FileSystem.readFile("package.json").then(value => value.toString())
    json = JSON.parse(json)

    console.log("Before:")
    console.log(json)
    await Promise.all([
        updateVersion(json.dependencies),
        updateVersion(json.devDependencies),
    ])
    console.log("After")
    console.log(json)
    await FileSystem.writeFile("package.json", JSON.stringify(json, null, 2))
    console.log("package.json file is upgraded.")
}

main()